<?php
namespace app\interfaces\controller;

use app\interfaces\model\MerchantGoods as GoodsModel;
use app\interfaces\model\Feedback as FeedbackModel;
use think\Cache;
use think\Db;
use think\Request;
use think\Exception;

class MerchantGoods
{
    /*
     * 商家端 - 商品管理
     * @param  string $shop_id  店铺ID
     * @param  string $state    上下架状态
     * @param  string $rank     排序
     */
    public function goods_list()
    {

        // 获取参数
        $data = Request::instance()->param();

        if (empty($data['shop_id']) || empty($data['state'])) throw new Exception('not Empty');

        // 搜索条件
        $condition['state'] = ['eq', $data['state']];
        $condition['member_id'] = ['eq', $data['shop_id']];

        if (empty($data['rank'])) $data['rank'] = 'create_time';

        // 排序
        $order = [$data['rank'] => 'desc'];

        // 条件
        if (!empty($data['title'])) $condition['title'] = ['like', '%' . $data['title'] . '%'];

        // 提交数据
        $model = new GoodsModel();

        $result = $model->where($condition)
            ->field('id,title,price,thumb_img,sale_number,inventory,pv,rebate_percentage')
            ->order($order)
            ->paginate(10);

        // 出售中 and 仓库
        $stat['sell'] = $model->where(['state' => '1', 'member_id' => $data['shop_id']])->count();
        $stat['warehouse'] = $model->where(['state' => '2', 'member_id' => $data['shop_id']])->count();

        if ($result) {
            return ['code' => 200, 'message' => '成功', 'data' => $result, 'stat' => $stat];
        }

        return ['code' => 403, 'message' => '网络繁忙'];


    }

    /*
     * 商家端 - 商品上下架管理
     * @param  string $shop_id   店铺ID
     * @param  string $goods_id  商品ID
     * @param  string $state     状态
     */
    public function put_away()
    {

        // 获取参数
        $data = Request::instance()->param();

        if (empty($data['shop_id']) || empty($data['goods_id']) || empty($data['state'])) throw new Exception('not Empty');

        if (($data['state'] < '1') && ($data['state'] > '2')) return ['code' => 401, 'message' => '状态参数不对'];

        // 提交数据
        $model = new GoodsModel();

        $result = $model->where(['member_id' => $data['shop_id'], 'id' => $data['goods_id']])->update(['state' => $data['state']]);

        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 403, 'message' => '网络繁忙'];


    }

    /*
     * 商家端 - 商品删除管理
     * @param  string $shop_id   店铺ID
     * @param  string $goods_id  商品ID
     */
    public function delete()
    {

        // 获取参数
        $data = Request::instance()->param();

        if (empty($data['shop_id']) || empty($data['goods_id'])) throw new Exception('not Empty');

        // 如果有购买中的商品
        $buy = Db::view('member_order_attached', 'goods_id,shop_order_number')
            ->view('member_order', 'shop_order_number,status', 'member_order.shop_order_number = member_order_attached.shop_order_number')
            ->where(['goods_id' => $data['goods_id'], 'status' => ['in', '1,2,6']])
            ->find();

        if (!empty($buy)) return ['code' => 401, 'message' => '该商品还有未收货或未退款的,请先处理'];

        // 启动事务
        Db::startTrans();
        try {

            // 删除商品
            Db::name('shop_goods')->where(['member_id' => $data['shop_id'], 'id' => $data['goods_id']])->delete();

            // 删除收藏中的该商品
            Db::name('member_collect')->where(['type_id' => '1', 'collect_id' => $data['goods_id']])->delete();

            // 删除浏览记录
            Db::name('member_browse')->where(['goods_id' => $data['goods_id']])->delete();

            // 删除限时抢购表
            Db::name('limited')->where(['goods_id' => $data['goods_id']])->delete();

            // 删除商品套餐表
            $find = Db::view('shop_goods_combo_selected', 'combo_id,goods_id')
                ->view('shop_goods_combo', 'id', 'shop_goods_combo.id = shop_goods_combo_selected.combo_id')
                ->where(['goods_id' => $data['goods_id']])
                ->find();

            if (!empty($find)) {
                // Db::view('shop_goods_combo_selected', 'combo_id,goods_id')
                //     ->view('shop_goods_combo', 'id', 'shop_goods_combo.id = shop_goods_combo_selected.combo_id')
                //     ->where(['goods_id' => $data['goods_id']])
                //     ->delete();
                Db::name('shop_goods_combo_selected')->where('combo_id',$find['combo_id'])->delete();
                Db::name('shop_goods_combo')->where('id',$find['combo_id'])->delete();
            }

            // 删除商品评价表
            Db::name('shop_goods_evaluate')->where(['goods_id' => $data['goods_id']])->delete();

            // 删除属性关联表
            Db::name('shop_spec_attr')->where(['goods_id' => $data['goods_id']])->delete();

            // 删除促销活动表
            Db::name('promotion')->where(['goods_id' => ['in', $data['goods_id']]])->delete();

            // 提交事务
            Db::commit();

            return ['code' => 200, 'message' => '成功'];

        } catch (\Exception $e) {

            // 回滚事务
            Db::rollback();

            return ['code' => 401, 'message' => '网络繁忙'];
        }

    }

    /*
     * 用户端 - 反馈提交
     * @param  string $type         分类
     * @param  string $content      反馈内容
     * @param  string $contact      联系方式
     */
    public function feedback_create()
    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $data = Request::instance()->param();

        if (empty($data['content'])) throw new Exception('not Empty');

        $data['ip'] = $this->getIP();


        if (!empty(Cache::get('ip_verify_' . ip2long($data['ip'])))) {
            return ['code' => 401, 'message' => '5分钟内只能反馈一次'];
        }

        Cache::set('ip_verify_' . ip2long($data['ip']), $data['ip'], 300); // 短信请求有效期

        $data['picArr'] = multi_upload();

        // 展示数据
        $model = new FeedbackModel();

        $result = $model->allowField(true)->save($data);

        if ($result) {
            return ['code' => 200, 'message' => '成功'];
        }

        return ['code' => 401, 'message' => '网络繁忙'];

    }

    // 获取IP
    protected function GetIP()
    {
        static $ip = NULL;
        if ($ip !== NULL) return $ip;

        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) unset($arr[$pos]);
            $ip = trim($arr[0]);
        } else if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } else if (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }

        //IP地址合法验证
        $ip = (false !== ip2long($ip)) ? $ip : '222.171.225.188';
        return $ip;
    }

}
